package com.directv.engineertools

import com.directv.engineertools.channelblocking.Channel

import grails.converters.XML
import grails.transaction.Transactional;

import java.util.Map;

import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.usermodel.Sheet
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.ss.usermodel.WorkbookFactory
import org.springframework.web.multipart.MultipartHttpServletRequest
import org.springframework.web.multipart.commons.CommonsMultipartFile
import org.grails.plugins.excelimport.*

class ChooseController {

	def excelImportService

	def index() {
	}

	def channelBlocking() {

	}

	@Transactional
	def upload(Integer max) {
		params.max = Math.min(max ?: 10, 100)
		/*
		 def f = request.getFile('myFile')
		 if (f.empty) {
		 flash.message = 'file cannot be empty'
		 render(view: 'channelBlocking')
		 return
		 }
		 String fileName = '/Users/yingliangdu/Projects/files/channels.xls'
		 f.transferTo(new File(fileName))
		 //response.sendError(200, 'Done')
		 */		
		//Import excel
		/*
		 ChannelExcelImporter importer = new ChannelExcelImporter(fileName);
		 def channelsMapList = importer.getChannels();
		 println channelsMapList
		 channelsMapList.each { Map channelParams ->
		 def newBook = new Book(bookParams)
		 if (!newBook.save()) {
		 println "Book not saved, errors = ${newBook.errors}"
		 }
		 }
		 */

		Map CONFIG_CHANNEL_COLUMN_MAP = [
			sheet:'NBC',
			startRow: 2,
			columnMap:  [
				'A':'providerID',
				'C':'providerName',
				'D':'channelNumber',
			]
		]
		
		Map propertyConfigurationMap = [
			providerID:([expectedType: ExpectedPropertyType.IntType, defaultValue:null])
		]

		MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request
		CommonsMultipartFile file = (CommonsMultipartFile) mpr.getFile("myFile")

		Workbook workbook = WorkbookFactory.create(file.inputStream)
		def channelList = excelImportService.columns(workbook, CONFIG_CHANNEL_COLUMN_MAP)
		//println channelList
		
		Channel channelInstance
		
		channelList.each { Map channelParamMap ->
			//println channelParamMap
			channelInstance = new Channel(channelParamMap)
			if (!channelInstance.hasErrors()) {
				/*
				println channelInstance.getProviderName()
				println channelInstance.getProviderID()
				println channelInstance.getProviderType()
				println channelInstance.getEffDate()
				*/
				channelInstance.save flush:true
			}
			else {
				println channelInstance.errors
			}
		  }
		
		render Channel.list() as XML
		
		//println Channel.list()

		/*
		Sheet sheet = workbook.getSheetAt(0)
		
		println sheet.getSheetName()
		println sheet.getProperties()

		for (int r = 1; r < sheet.getPhysicalNumberOfRows(); r++) {
			// get our fields
			Row row = sheet.getRow(r)
			//def theName = row.getCsheet.getrgetCell(0, r).contents
			println row.getCell(2)
		}
		*/

		//respond Channel.list(params), model:[channelInstanceCount: Channel.count()]
	}
}
